package com.mediocre.eg4routing;

import com.mediocre.constant.Constants;
import com.mediocre.util.CommonUtils;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * exchange模式：路由模式（直接模式）
 * Receiving messages selectively
 * 生产者设置消息的routingK，消费者根据routingKey筛选自己感兴趣的消息
 * 和前面的例子相比，消费者在绑定队列和exchange的同时，还另外绑定了一个routingKey，它是一个关键字，用于筛选自己感兴趣的消息，只有某条消息匹配了该routingKey，才接收该消息
 */
public class ReceiveLogsDirect {

    public static void main(String[] args) throws IOException, TimeoutException {
        final Channel channel = CommonUtils.getChannel();

        channel.exchangeDeclare(Constants.EXCHANGE_NAME_DIRECT, BuiltinExchangeType.DIRECT);

        String queueName = channel.queueDeclare().getQueue();

        if (args.length < 1) {
            System.err.println("Usage: ReceiveLogsDirect [info] [warning] [error]");
            System.exit(1);
        }

        for (String severity: args) {
            // 此处routingKey参数，绑定了queue对exchange中感兴趣的路由关键字（severity），比如此处可以为 error
            channel.queueBind(queueName, Constants.EXCHANGE_NAME_DIRECT, severity);
        }

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };

        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> {});
    }
}
